const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
const http = require('http');
const { Server } = require('socket.io');
const db = require('./config/db');

// 加载环境变量
dotenv.config();

// 初始化Express应用
const app = express();
const PORT = process.env.PORT || 5000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 路由导入
const authRoutes = require('./routes/auth');
const productRoutes = require('./routes/product');
const adminRoutes = require('./routes/admin'); // 导入管理员路由
const announcementRoutes = require('./routes/announcement'); // 导入公告路由
const sellerRoutes = require('./routes/seller'); // 导入卖家路由
const buyerRoutes = require('./routes/buyer'); // 导入买家路由
const chatRoutes = require('./routes/chat'); // 导入聊天路由
const transactionRoutes = require('./routes/transaction'); // 导入交易路由

// 路由使用
app.use('/api/auth', authRoutes);
app.use('/api/product', productRoutes);
app.use('/api/admin', adminRoutes); // 注册管理员路由
app.use('/api/announcements', announcementRoutes); // 注册公告路由（修正为复数形式）
app.use('/api/seller', sellerRoutes); // 注册卖家路由
app.use('/api/buyer', buyerRoutes); // 注册买家路由
app.use('/api/chat', chatRoutes); // 注册聊天路由
app.use('/api', transactionRoutes); // 注册交易路由

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    success: false,
    message: 'Server error',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 设置WebSocket服务器
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 存储用户的socket连接
global.io = io;
global.users = {};

// 处理WebSocket连接
io.on('connection', (socket) => {
  console.log(`[${new Date().toLocaleString()}] [INFO] 新WebSocket连接建立，socket id: ${socket.id}`);

  // 用户登录时，将其socket id与用户id关联
  socket.on('login', (data) => {
    const userId = data.data.userId;
    global.users[userId] = socket.id;
    console.log(`[${new Date().toLocaleString()}] [INFO] 用户${userId}登录，socket连接已关联: ${socket.id}`);
    // 更新数据库中用户的登录状态为1
    db.query('UPDATE users SET login = 1 WHERE user_id = ?', [userId], (err) => {
      if (err) {
          console.error(`[${new Date().toLocaleString()}] [ERROR] 更新用户${userId}登录状态失败: ${err.message}`);
        } else {
          console.log(`[${new Date().toLocaleString()}] [INFO] 用户${userId}登录状态已更新为在线`);
        }
    });

  });

  // 断开连接时，移除用户的socket id
  socket.on('disconnect', () => {
    console.log(`[${new Date().toLocaleString()}] [INFO] WebSocket连接断开，socket id: ${socket.id}`);
    console.log(`[${new Date().toLocaleString()}] [DEBUG] 当前在线用户: ${JSON.stringify(global.users)}`);
    let found = false;
    let userIdFound = null;
    for (const userId in global.users) {
      console.log(`[${new Date().toLocaleString()}] [DEBUG] 检查用户: ${userId}, socket id: ${global.users[userId]}`);
      if (global.users[userId] === socket.id) {
        found = true;
        userIdFound = userId;
        delete global.users[userId];
        console.log(`[${new Date().toLocaleString()}] [DEBUG] 已从在线用户列表移除用户: ${userId}`);
        break;
      }
    }
    if (found && userIdFound) {
      console.log(`[${new Date().toLocaleString()}] [DEBUG] 准备更新用户${userIdFound}的离线状态`);
      // 更新数据库中用户的登录状态为0
      db.query('UPDATE users SET login = 0 WHERE user_id = ?', [userIdFound], (err) => {
        if (err) {
          console.error(`[${new Date().toLocaleString()}] [ERROR] 更新用户${userIdFound}离线状态失败: ${err.message}`);
        } else {
          console.log(`[${new Date().toLocaleString()}] [INFO] 用户${userIdFound}已离线，数据库状态更新成功`);
        }
      });
    } else {
      console.log(`[${new Date().toLocaleString()}] [WARN] 未找到与socket id ${socket.id}关联的用户`);
    }
  });
});

// 启动服务器
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

module.exports = app;